//
//  CityViewController.m
//  FVQuickMessage
//
//  Created by dllo on 16/8/19.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "CityViewController.h"
#import "NetTool.h"
#import "CityModel.h"
#import "WeatherViewController.h"

@interface CityViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *modelArray;

@property (nonatomic, retain) NSMutableArray *keyArray;

@property (nonatomic, retain) NSDictionary *dictionary;

@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, assign) BOOL isSearch;

@property (nonatomic, retain) NSMutableArray *searchArray;

@property (nonatomic ,retain) NSMutableArray *nameArray;

@property (nonatomic, retain) CityModel *cityModel;

@end

@implementation CityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self config];
    
    [self hanleData];
    
    [self creteTableView];
    
}

-(void)config {
    
    self.cityModel = [[CityModel alloc] init];
    self.searchArray = [[NSMutableArray alloc] init];
    self.nameArray = [[NSMutableArray alloc] init];
    self.keyArray = [[NSMutableArray alloc] init];
    self.modelArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"城市";
    self.navigationController.navigationBar.translucent = NO;
    
}

-(void)hanleData {
    
    [NetTool GET:@"http://api.k780.com:88/?app=weather.city&format=json" body:nil response:FVJSON headerFile:nil success:^(id result) {
        
        self.dictionary = [result objectForKey:@"result"];
        
        /*for (NSDictionary *dic in self.dictionary) {
            
            CityModel *model = [[CityModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.modelArray addObject:model];
            
        }*/
        
        for (NSString *key in self.dictionary) {
            
            CityModel *model = [[CityModel alloc] init];
            
            [model setValuesForKeysWithDictionary:[self.dictionary objectForKey:key]];
            
            [self.modelArray addObject:model];
            
            [self.nameArray addObject:model.citynm];
            
            [self.keyArray addObject:key];
            
        }
        
        [self.tableView reloadData];
        
        
        
        
    } failure:^(NSError *error) {
       
        NSLog(@"%@", error);
        
    }];
    
}

-(void)creteTableView {
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    
    self.searchBar.placeholder = @"请输入您想搜索的城市";
    
    [self.view addSubview:_searchBar];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    self.searchBar.showsCancelButton = YES;
    
    self.searchBar.delegate = self;
    
    self.tableView.backgroundColor = [UIColor colorWithRed:0.94f green:0.94f blue:0.96f alpha:1.00f];
    [self.view addSubview:_tableView];
    
    self.tableView.tableHeaderView = self.searchBar;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.isSearch) {
        return self.searchArray.count;
    }
    
    return self.modelArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CityModel *model = [self.modelArray objectAtIndex:indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (self.isSearch) {
        cell.textLabel.text = [self.searchArray objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = model.citynm;
    }
    
    
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WeatherViewController *weatherVC = [[WeatherViewController alloc] init];
    
    if (self.isSearch) {
        
        NSString *cityKey = [[NSString alloc] init];
        
        for (CityModel *model in self.modelArray) {
            
            NSString *citynm = [self.searchArray objectAtIndex:indexPath.row];
            
            if ([citynm isEqualToString:model.citynm]) {
                
                self.cityModel = model;
                
            }
            
        }
        
        for (NSString *key in self.keyArray) {
            
            CityModel *model = [[CityModel alloc] init];
            
            [model setValuesForKeysWithDictionary:[self.dictionary objectForKey:key]];
            
            if (self.cityModel == model) {
                cityKey = key;
            }
            
        }
        
        weatherVC.cityID = cityKey;
        
    } else {
        
        NSString *cityKey = [NSString string];
        
        CityModel *ctmodel = [self.modelArray objectAtIndex:indexPath.row];
        
        for (NSString *key in self.keyArray) {
            
            CityModel *model = [[CityModel alloc] init];
            
            [model setValuesForKeysWithDictionary:[self.dictionary objectForKey:key]];
            
            if (ctmodel == model) {
                cityKey = key;
            }
            
        }
        
        NSLog(@"%@", cityKey);
        
        weatherVC.cityID = cityKey;
        
    }
    
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    self.isSearch = NO;
    [self.tableView reloadData];
    [searchBar resignFirstResponder];
    
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    [self filterBySubstring:searchText];
    
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self filterBySubstring:searchBar.text];
    
    [searchBar resignFirstResponder];
    
}

-(void)filterBySubstring:(NSString *)subStr {
    
    self.isSearch = YES;
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd]%@", subStr];
    
    self.searchArray = (NSMutableArray *)[self.nameArray filteredArrayUsingPredicate:pred];
    
    [self.tableView reloadData];
    
}

-(void)viewWillDisappear:(BOOL)animated {
    
    self.navigationController.navigationBar.translucent = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
